package com.fenxiao.user.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.fenxiao.util.Tools;
import com.fenxiao.agent.entity.Agent;
import com.fenxiao.common.Pager;
import com.fenxiao.base.BaseDaoImpl;
import com.fenxiao.user.dao.UserDao;
import com.fenxiao.user.entity.User;


@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {
	private  SessionFactory sessionFactory;

	//登陆
	public User queryUser(String userLoginName) {
		String hql="from User u where u.userLoginName ='"+userLoginName+"'";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		Object obj=query.uniqueResult();
		if(obj!=null){ 
			return (User)obj;
		}else{
		return null;
		}
	}

	/**
	    * 查询所有记录数
	    * @param hql 查询的条件
	    * @return 总记录数
	    */
		public int getAllRowCount(String hql) {
			Session session=sessionFactory.openSession();
			List list=null;
			try{
				Query query=session.createQuery(hql);
			
				list=query.list();
				
			}catch (RuntimeException e) {
			   throw e;
			}
			session.close();
			return list.size();
			
		}
		/**
	    * 分页查询
	    * @param hql 查询的条件
	    * @param offset 开始记录
	    * @param length 一次查询几条记录
	    * @return
	    */
		public List  queryForPage(String hql, int offset, int length) {
			Session session=sessionFactory.openSession();
			List  list=null;
			try{
				Query query=session.createQuery(hql);
				query.setFirstResult(offset);
	           query.setMaxResults(length);
	           list=query.list();
				
			}catch (RuntimeException e) {
			   throw e;
			}
			session.close();
			return list;
		}
		/**
	    * 查询所有记录数(原生态sql)
	    * @param hql 查询的条件
	    * @return 总记录数
	    */
		public int getAllSQLRowCount(String hql) {
			Session session=sessionFactory.openSession();
			List list=null;
			try{
				Query query=session.createSQLQuery(hql);
			
				list=query.list();
				
			}catch (RuntimeException e) {
			   throw e;
			}
			session.close();
			return list.size();
			
		}
		/**
	    * 分页查询
	    * @param sql 查询的条件
	    * @param offset 开始记录
	    * @param length 一次查询几条记录
	    * @return
	    */
		public List  querySQLForPage(String hql, int offset, int length) {
			Session session=sessionFactory.openSession();
			List  list=null;
			try{
				Query query=session.createSQLQuery(hql);
				query.setFirstResult(offset);
	           query.setMaxResults(length);
	           list=query.list();
				
			}catch (RuntimeException e) {
			   throw e;
			}
			session.close();
			return list;
		}
		     
		 /**
	     * 分页查询员工佣金	
	     */
		public Pager queryPageForStaff(int pageSize,int page,String search, long agentId){
			String hql="from User u where(u.agentsId IN (select a.agentId from Agent a where a.partnerId="+agentId+") "
					+ "or u.agentsId="+agentId+")";
			
			
			 if(search!=null&&!"".equals(search.trim())){
				 hql+="and (u.username like'%"+search+"%' or u.nickName like'%"+search+"%' or u.mobile like'%"+search+"%')";
			 }
			 System.out.println(hql);
			int allRow =this.getAllRowCount(hql);    //总记录数
		       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
		       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
		       final int length = pageSize;    //每页记录数
		       final int currentPage = Pager.countCurrentPage(page);
		       List list = this.queryForPage(hql,offset, length); //"一页"的记录
		       
		       
		     //把分页信息保存到Bean中
		       Pager pages = new Pager();
		       pages.setPageSize(pageSize);    
		       pages.setCurrentPage(currentPage);
		       pages.setAllRow(allRow);
		       pages.setTotalPage(totalPage);
		       pages.setList(list);
		       pages.init();
		       return pages;
			   
			
		}
		
		

	
	@Override
	public User queryMoneyOfUser(String openId) {
		// TODO Auto-generated method stub
		String hql="from User u where u.weChatId='"+openId+"'";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		Object obj=query.uniqueResult();
		if(obj!=null){
			return (User) obj;
		}else {
			return null;
		}
		
	}
	
	@Override
	public User queryUserById(Long userId) {
		// TODO Auto-generated method stub
		String hql="select u from User u where u.id="+userId+"and u.subscribe=1";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		Object obj=query.uniqueResult();
		if(obj!=null){
			return (User) obj;
		}else{
			return null;
		}
	}
	
	@Override
	public int updateBalanceOfUser(Double money,long userId) {
		// TODO Auto-generated method stub
		String hql="update User u set u.balance="+money+" where u.id="+userId+" and u.subscribe=1";
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public User queryUserUnSubscribe() {
		// TODO Auto-generated method stub
		String hql="select u from User u where u.weChatId is null";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		Object obj=query.uniqueResult();
		return (User) obj;
	}
	
	
	
	@Override
	public int updateUser(User user,long userId) {
		// TODO Auto-generated method stub
		String hql="update User u set u.nickName='"+user.getNickName()+"',u.userPhoto='"+user.getUserPhoto()+"',u.sex="+user.getSex()+",u.regTime='"+user.getRegTime()+"',u.weChatId='"+user.getWeChatId()+"' where u.id="+userId+" and u.subscribe=1";
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public int updateUserByOpenId(User user) {
		// TODO Auto-generated method stub
		String hql="update User u set u.mobile='"+user.getMobile()+"',u.username='"+user.getUsername()+"',u.userPassword='"+user.getUserPassword()+"' where u.weChatId='"+user.getWeChatId()+"' and u.subscribe=1";
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public int updateUserForCompleteRegisteration(User user) {
		// TODO Auto-generated method stub
		String hql="update User u set u.nickName='"+user.getNickName()+"',u.userPhoto='"+user.getUserPhoto()+"',u.sex='"+user.getSex()+"',u.regTime='"+user.getRegTime()+
				"',u.subscribe=1 where u.weChatId='"+user.getWeChatId()+"'";
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public User weixinLogin(User user) {
		// TODO Auto-generated method stub
		String hql="select u from User u where u.mobile='"+user.getMobile()+"' and u.userPassword='"+user.getUserPassword()+"' and u.subscribe=1";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		Object obj=query.uniqueResult();
		return (User) obj;
	}

	
	@Override
	public String getRecommendCode() {
//		// TODO Auto-generated method stub
//		
//		String recomCode = Tools.recomCodePrefix+Tools.recomCodeSuffix;
//		
//		String hql="select max(recommendationCode) from User";
//		Query query=sessionFactory.getCurrentSession().createQuery(hql);
//		String obj=(String) query.uniqueResult();
//		if(obj==null){
//			return recomCode;
//		}else{
//			String codes= obj.substring(obj.length()-8, obj.length());
//			 int codei = Integer.parseInt(codes)+1;
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");//
				String	timestr = sdf.format( new Date());//只能用字符串接收,data为Date date = new Date();
//				System.err.println("Tools.recomCodePrefix+timestr+String.format('%08d', codei):----------"+Tools.recomCodePrefix+timestr+String.format("%08d", codei));
			return Tools.recomCodePrefix+timestr;//+String.format("%08d", codei)
//		}
		
	}
	
	@Override
	public int updateUserAfterSubscribe(User user) {
		// TODO Auto-generated method stub
		String hql="update User u set u.mobile='"+user.getMobile()+"',u.username='"
		+user.getUsername()+"',u.userPassword='"
		+user.getUserPassword()+"',u.province='"+user.getProvince()+"',"
				+ "u.city='"+user.getCity()+"',u.area='"+user.getArea()+"', u.userQr='"+user.getUserQr()+"',u.recommendationCode='"+user.getRecommendationCode()+"',u.userLevel="+user.getUserLevel()+" where u.weChatId='"
		+user.getWeChatId()+"'";
		
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public List<User> queryTeamOfTheUser(User user,Integer userLevel,String search) {
		// TODO Auto-generated method stub
		String hql="select u from User u where u.recomCode='"+user.getRecommendationCode()+"' and u.subscribe=1";
		String hql1="and u.userLevel="+userLevel;
		String hql2="and u.nickName like '"+"%"+search+"%"+"'";
		if(userLevel!=null){
			hql+=hql1;
		}
		if(search!=null){
			hql+=hql2;
		}
		hql+="order by u.regTime  desc";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		List<User> list=query.list();
		if(list!=null){
			return list;
		}else{
			return null;
		}
		
	}
	
	@Override
	public int updateUpdateUnsubscribe(String openId) {
		// TODO Auto-generated method stub
		String hql="update User u set u.subscribe=0 where u.weChatId='"+openId+"'";
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public int resetPassword(long userId, String password) {
		// TODO Auto-generated method stub
		String hql="Update User u set u.presentPass='"+password+"' where u.id="+userId;
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	
	@Override
	public int updateUserByMobile(User user) {
		// TODO Auto-generated method stub
		String hql="update User u set u.userPassword='"+user.getUserPassword()+"' where u.mobile="+user.getMobile();
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}


	  /**
     * 分页查询员工	
     */
     public Pager queryUserPage(int pageSize,int page,String search, long agentId){
    	 String hql="from User u where u.userLevel=3 and u.agentsId="+agentId;
			
			
			 if(search!=null&&!"".equals(search.trim())){
				 hql+="and (u.username like'%"+search+"%' or u.nickName like'%"+search+"%' or u.mobile like'%"+search+"%')";
			 }
			 System.out.println(hql);
			int allRow =this.getAllRowCount(hql);    //总记录数
		       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
		       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
		       final int length = pageSize;    //每页记录数
		       final int currentPage = Pager.countCurrentPage(page);
		       List list = this.queryForPage(hql,offset, length); //"一页"的记录
		       
		       
		     //把分页信息保存到Bean中
		       Pager pages = new Pager();
		       pages.setPageSize(pageSize);    
		       pages.setCurrentPage(currentPage);
		       pages.setAllRow(allRow);
		       pages.setTotalPage(totalPage);
		       pages.setList(list);
		       pages.init();
		       return pages;
	
		}
     /**
 	 * 添加员工
 	 */
 	public int addUser(User user){
 		this.sessionFactory.getCurrentSession().save(user);
 		return 1;
 	}
	
 	/**
	 * 批量删除员工
	 */
	public int deleteUser(String num){
		
	String hql="delete User u where u.id in ("+num+")";	
	 int i=this.sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	 if(i>0){
		 return i;
	 }else{
		return 0; 
	 }
	}
	/**
	 * 删除员工
	 */
	public int deleteUser1(long id){

		try{
		User user =(User)sessionFactory.getCurrentSession().load(User.class, id);
		
		sessionFactory.getCurrentSession().delete(user);
		return 1;
		}catch(Exception e){
			return 0;
		}
		
	}
	/**
	 * 查询详情
	 */
	public User queryUserInfo(User user){
		String hql="from User u where u.id="+user.getId();
	    Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
	    Object obj=query.uniqueResult();
	    if(obj!=null){
	    	return (User) obj;
	    }else{
	    	return null;
	    	}
	    }
	/**
	 * 分页查询所有的会员
	 */
	public Pager queryAllUserPage(int pageSize,int page,String search){
		String hql="from User u where u.userLevel<>2";
		
		
		 if(search!=null&&!"".equals(search.trim())){
			 hql+="and (u.username like'%"+search+"%' or u.nickName like'%"+search+"%' or u.mobile like'%"+search+"%')";
		 }
		 System.out.println(hql);
		int allRow =this.getAllRowCount(hql);    //总记录数
	       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	       final int length = pageSize;    //每页记录数
	       final int currentPage = Pager.countCurrentPage(page);
	       List list = this.queryForPage(hql,offset, length); //"一页"的记录
	       
	       
	     //把分页信息保存到Bean中
	       Pager pages = new Pager();
	       pages.setPageSize(pageSize);    
	       pages.setCurrentPage(currentPage);
	       pages.setAllRow(allRow);
	       pages.setTotalPage(totalPage);
	       pages.setList(list);
	       pages.init();
	       return pages;
	}	
	/**
	 * 查询所有的会员
	 */
	public List<User> queryUserList(){
		String hql="from User ";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		List<User> list=query.list();
		if(list!=null){
			return list;
		}else{
			return null;
		}
	}
	/**
	 * 修改
	 */
	public int updateUser(User user){
		this.sessionFactory.getCurrentSession().update(user);
		return 1;
	}
	/**
	 * 修改genxinxi
	 */
	public int updateUsergeren(User user){
		String hql = "update User u set u.userPhoto='"+user.getUserPhoto()+"' where u.id="+user.getId();
		int result= sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
		return 1;
	}
	
	@Override
	public User checkMobile(String mobile) {	
		// TODO Auto-generated method stub
		String hql="select u from User u where u.mobile='"+mobile+"'";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		User user=(User) query.uniqueResult();
		if(user!=null){
			return user;
		}else{
		return null;
		}
		}
	/**
	 * 查询user
	 */
	 public User queryUserSadff(String recode){
		 String hql="from User u where u.recommendationCode='"+recode+"'";
		Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
		Object obj=query.uniqueResult();
		if(obj!=null){
			return (User)obj;
		}else{
			return null;
		}
	 }
	 /**
	  * 查询员工
	  */
	 public User queryUserSdf(long sadffId){
		 String hql="from User u where u.sadffId="+sadffId;
		 Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
		 Object obj =query.uniqueResult();
		 if(obj!=null){
				return (User)obj;
			}else{
				return null;
			}
	 }
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List<User> queryGetAll(Long userid) {
		 String hql="select u from User u where u.sadffId="+userid+" and u.subscribe=1  order by u.regTime  desc";
			Query query=sessionFactory.getCurrentSession().createQuery(hql);
			List<User> list=query.list();
			if(list!=null){
				return list;
			}else {				
				return null;
			}
	}
	/**
	 * 分页查询直属团队
	 */
	
	@Override
	public Pager queryZhishu(int pageSize, int page, String search, User user) {
		String hql="from User u where u.recomCode='"+user.getRecommendationCode()+"' and u.subscribe=1";
		
		
		 if(search!=null&&!"".equals(search.trim())){
			 hql+="and (u.username like'%"+search+"%' or u.nickName like'%"+search+"%' or u.mobile like'%"+search+"%')";
		 }
		 hql+="order by u.regTime  desc";
		int allRow =this.getAllRowCount(hql);    //总记录数
	       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	       final int length = pageSize;    //每页记录数
	       final int currentPage = Pager.countCurrentPage(page);
	       List list = this.queryForPage(hql,offset, length); //"一页"的记录
	       
	       
	     //把分页信息保存到Bean中
	       Pager pages = new Pager();
	       pages.setPageSize(pageSize);    
	       pages.setCurrentPage(currentPage);
	       pages.setAllRow(allRow);
	       pages.setTotalPage(totalPage);
	       pages.setList(list);
	       pages.init();
	       return pages;
	}
	/**
	 * 分页查询全部成员
	 */
	@Override
	public Pager queryQuanbu(int pageSize, int page, String search, User user) {
		String hql="select u from User u where u.sadffId="+user.getId()+" and u.subscribe=1";
		
		
		 if(search!=null&&!"".equals(search.trim())){
			 hql+="and (u.username like'%"+search+"%' or u.nickName like'%"+search+"%' or u.mobile like'%"+search+"%')";
		 }
		 hql+="order by u.regTime  desc";
		int allRow =this.getAllRowCount(hql);    //总记录数
	       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	       final int length = pageSize;    //每页记录数
	       final int currentPage = Pager.countCurrentPage(page);
	       List list = this.queryForPage(hql,offset, length); //"一页"的记录

	     //把分页信息保存到Bean中
	       Pager pages = new Pager();
	       pages.setPageSize(pageSize);    
	       pages.setCurrentPage(currentPage);
	       pages.setAllRow(allRow);
	       pages.setTotalPage(totalPage);
	       pages.setList(list);
	       pages.init();
	       return pages;
	}
	/**
	 * 审核失败后返还钱
	 * */
	@Override
	public int updateBalanceUsermonye(Double money, long userId) {
		String hql="update User u set u.balance="+money+" where u.id="+userId+" and u.subscribe=1";
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}

	@Override
	public List queryUseragent(long agentId) {
		String hql="from User u where u.agentsId="+agentId;
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		List<User> list=query.list();
		if(list!=null){
			return list;
		}else{
			return null;
		}
	}


	/*@Override
	public int updateBalanceOfUser(Double money, long userId) {
		// TODO Auto-generated method stub
		return 0;
	}*/

	
	
}
